package com.jinlejia.erp.ui.message;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.MessageDetailsAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.common.WrapContentLinearLayoutManager;
import com.jinlejia.erp.databinding.ActivitySearchMessageBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;


/**
 * 消息搜索
 */

public class SearchMessageActivity extends AppCompatActivity implements YfLoadMoreListener {
    private String url;
    private int page=1, pageSize;

    private MessageDetailsAdapter adapter;
    private boolean mLoadingLock = false;
    private ActivitySearchMessageBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search_message);
        binding.btBack.setOnClickListener(this::onClick);
        binding.btClear.setOnClickListener(this::onClick);
        initView();
        initEvent();
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        adapter.setOnItemClickListener((view, o) -> {
            Intent intent = new Intent(SearchMessageActivity.this, MessageContentActivity.class);
            intent.putExtra("objectId", ((Map<String, Object>) o).get("objectId").toString());
            intent.putExtra("time","2021");
            startActivity(intent);
        });
    }

    /**
     * 初始化视图
     */
    private void initView() {
        url = ApiConfig.MESSAGE_SEARCH.concat("page." + page).concat("/pageSize.20");
        binding.yfrvSearchResult.setHasFixedSize(true);
        binding.yfrvSearchResult.setLayoutManager(new WrapContentLinearLayoutManager(this));
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        adapter = new MessageDetailsAdapter(dataList);
        binding.yfrvSearchResult.setAdapter(adapter);
        adapter.changeMode(YfListMode.MODE_EMPTY);
        binding.yfrvSearchResult.enableAutoLoadMore(this);
        binding.etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    binding.btClear.setVisibility(View.VISIBLE);
                    page=1;
                    getData();
                } else {
                    binding.btClear.setVisibility(View.INVISIBLE);
                    adapter.changeMode(YfListMode.MODE_EMPTY);
                }
            }
        });

    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_clear:
                binding.etSearchText.setText("");
                break;
        }
    }

    private void getData() {
        mLoadingLock = true;
        OkHttpUtils
                .get()
                .url(url)
                .addParams("key", binding.etSearchText.getText().toString())
                .addParams("type", "2021")
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(SearchMessageActivity.this, response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("list").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (page == 1) {
                                adapter.setData(list);
                            } else {
                                adapter.addData(list);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void loadMore() {
        if (adapter.getData().size() % 20 == 0) {
            if (mLoadingLock) {
                return;
            }
            mLoadingLock = true;
            page++;
            adapter.addFooter("loading");

            getData();
        } else {
            adapter.addFooter(R.string.is_all);
        }
    }
}
